using UnityEditor;
using UnityEngine;

namespace AutoInjector.Editor
{
    [CustomPropertyDrawer(typeof(AutoInjectAttribute))]
    public class AutoInjectDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(position, label, property);
            EditorGUI.PropertyField(position, property, label);
            EditorGUI.EndProperty();
            
            if (property.propertyType != SerializedPropertyType.ObjectReference || 
                property.objectReferenceValue != null)
            {
                return;
            }

            var attr = attribute as AutoInjectAttribute;
            Object obj = null;
            switch (attr.searchScope)
            {
                case SearchScope.Project:
                    obj = Finder.SearchInProject(fieldInfo.FieldType, attr.filterPattern);
                    break;
                case SearchScope.Scene:
                    obj = AutoInjector.Finder.SearchInScene(fieldInfo.FieldType, attr.filterPattern);
                    break;
                case SearchScope.GameObject:
                    var go = (property.serializedObject.targetObject as Component).gameObject;
                    obj = go.Search(fieldInfo.FieldType, attr.filterPattern);
                    break;
            }

            if (obj == null)
            {
                return;
            }

            property.objectReferenceValue = obj;
            property.serializedObject.ApplyModifiedProperties();
        }
    }
}